<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\1\11 0011
 * Time: 10:43
 */
namespace backend\controllers;

use common\helps\pageTools;
use common\models\Responses;

use Yii;
use Elasticsearch\ClientBuilder;

class SearchAllController extends BaseController {
    public static $hosts = ['192.168.1.203'];
    public $params = [];
//    public $freeAccess = true;
    public $freeAccessActions = [];

    public function behaviors()
    {
        return [
            'ghost-access' => [
                'class' => GhostAccessControl::className(),
            ],
        ];
    }

    public function actionIndex()
    {
        $data = [];
        $postion = \Yii::$app->request->get('postion', 1);//分类 1全部2资产包3项目
        $keyWords = strtolower(\Yii::$app->request->get('keyWords', ''));     //关键词
        $paramArr['principal'] = \Yii::$app->request->get('principal', 0);   //金额
        $paramArr['category'] = \Yii::$app->request->get('category', 0);    //资产包类别
        $paramArr['packageState'] = \Yii::$app->request->get('packageState', 0); //当前状态
        $paramArr['packageType'] = intval(\Yii::$app->request->get('packageType', 0)); //资产包类型
        $paramArr['owner'] = \Yii::$app->request->get('owner', '');            //上传人
        $paramArr['province'] = intval(\Yii::$app->request->get('province', 0));      //省份
        $paramArr['city'] = intval(\Yii::$app->request->get('city', 0));          //城市
        $paramArr['leader'] = trim(\Yii::$app->request->get('leader', ''));        //责任人
        $paramArr['teams'] = trim(\Yii::$app->request->get('teams', ''));         //团队人
        $paramArr['industry'] = \Yii::$app->request->get('industry', '');     //行业
        $paramArr['mortgageType'] = \Yii::$app->request->get('diyawu', '');     //抵押物类型
        $orderNum = \Yii::$app->request->get('order', '0');     //排序
        $is_suit = \Yii::$app->request->get('packageType', -2);    //诉讼
        $paramArr['is_suit'] = $is_suit==''?-2:intval($is_suit);    //诉讼
        $is_title =  \Yii::$app->request->get('is_title', 2);//1是标题 2是名字
        $paramArr['is_package'] = \Yii::$app->request->get('is_package', 1);//1是资产包 2是单项目

        $size = \Yii::$app->request->get('size', 10);  //显示个数
        $from = \Yii::$app->request->get('from', 0)*$size;   //显示第几页
        $page = \Yii::$app->request->get('from', 0);   //显示第几页
        $TKeyWords = self::actionGetAnalyzer($keyWords);
        if (!empty($TKeyWords)){
            $data['normalStr']=$TKeyWords['normalStr'];
            $data['tagStr']=$TKeyWords['tagStr'];
        }else{
            $data['normalStr']=['//'];
            $data['tagStr']=[''];
        }
        switch ($postion){
            case 1:
                $allData = self::actionSetAllData1($is_title,$keyWords,$orderNum,$size,$from);
                if (empty($allData)){
                    $allData = self::actionSetAllData1(1,$keyWords,$orderNum,$size,$from);
                }
                //分页
                $url = preg_replace('/&from=\d*/','',Yii::$app->request->getHostInfo().Yii::$app->request->url);
                $pageUrl = [];
                $pageUrl['action'] = 'search-all';
                $pageUrl['location'] = 'index';
                $pageUrl['condition'] = '?' . parse_url($url, PHP_URL_QUERY);
                $data['pageString'] = pageTools::createPageString($pageUrl, $allData['data']['count'], $page, $size);
                $data['count'] = $allData['data']['count'];
                $data['allRes'] = $allData['data']['res'];
                $data['packageTeam'] = self::actionGetPackageTeam()['data']['res'];
                $data['projectTeam'] = self::actionGetProjectTeam()['data']['res'];
                $data['user'] = self::actionGetUser()['data']['res'];
                $data['authItem'] = self::actionGetAuthitem()['data']['res'];
                $data['packageTransfer'] = self::actionGetPackageTransfer()['data']['res'];
                $data['postion'] = 1;
                return $this->render('index',$data);
                break;
            case 2:
                $packageData = self::actionSetPackageData($is_title,$keyWords,$orderNum,$size,$from,$paramArr);
                if (empty($packageData)){
                    $packageData = self::actionSetPackageData(1,$keyWords,$orderNum,$size,$from,$paramArr);
                }
                $url = preg_replace('/&from=\d*/','',Yii::$app->request->getHostInfo().Yii::$app->request->url);
                $pageUrl = [];
                $pageUrl['action'] = 'search-all';
                $pageUrl['location'] = 'index';
                $pageUrl['condition'] = '?' . parse_url($url, PHP_URL_QUERY);
                $data['pageString'] = pageTools::createPageString($pageUrl, $packageData['data']['count'], $page, $size);
                $data['count'] = $packageData['data']['count'];
                $data['package'] = $packageData['data']['res'];
                $data['user'] = self::actionGetUser()['data']['res'];
                $data['packageTransfer'] = self::actionGetPackageTransfer()['data']['res'];
                $data['packageTeam'] = self::actionGetPackageTeam()['data']['res'];
                $data['authItem'] = self::actionGetAuthitem()['data']['res'];
                $data['provinceData'] = \backend\models\SearchPackage::getProvinces('pid=0');
                $data['postion'] = 2;
                return $this->render('index',$data);
                break;
            case 3:
                $projectData = self::actionSetProjectData($is_title,$keyWords,$orderNum,$size,$from,$paramArr);
                if (empty($projectData)){
                    $projectData = self::actionSetProjectData(1,$keyWords,$orderNum,$size,$from,$paramArr);
                }
                $url = preg_replace('/&from=\d*/','',Yii::$app->request->getHostInfo().Yii::$app->request->url);
                $pageUrl = [];
                $pageUrl['action'] = 'search-all';
                $pageUrl['location'] = 'index';
                $pageUrl['condition'] = '?' . parse_url($url, PHP_URL_QUERY);
                $data['pageString'] = pageTools::createPageString($pageUrl, $projectData['data']['count'], $page, $size);
                $data['count'] = $projectData['data']['count'];
                $data['project'] = $projectData['data']['res'];
                $data['user'] = self::actionGetUser()['data']['res'];
                $data['projectTeam'] = self::actionGetProjectTeam()['data']['res'];
                $data['authItem'] = self::actionGetAuthitem()['data']['res'];
                $data['provinceData'] = \backend\models\SearchPackage::getProvinces('pid=0');
                $data['postion'] = 3;
                return $this->render('index',$data);
                break;
            default:
                $allData = self::actionSetAllData($is_title,$keyWords,$orderNum,$size,$from);
                if (empty($allData)){
                    $allData = self::actionSetAllData(1,$keyWords,$orderNum,$size,$from);
                }
                $url = preg_replace('/&from=\d*/','',Yii::$app->request->getHostInfo().Yii::$app->request->url);
                $pageUrl = [];
                $pageUrl['action'] = 'search-all';
                $pageUrl['location'] = 'index';
                $pageUrl['condition'] = '?' . parse_url($url, PHP_URL_QUERY);
                $data['pageString'] = pageTools::createPageString($pageUrl, $allData['data']['count'], $page, $size);
                $data['count'] = $allData['data']['count'];
                $data['allRes'] = $allData['data']['res'];
                $data['packageTeam'] = self::actionGetPackageTeam()['data']['res'];
                $data['projectTeam'] = self::actionGetProjectTeam()['data']['res'];
                $data['user'] = self::actionGetUser()['data']['res'];
                $data['authItem'] = self::actionGetAuthitem()['data']['res'];
                $data['packageTransfer'] = self::actionGetPackageTransfer()['data']['res'];
                $data['postion'] = 1;
                return $this->render('index',$data);
                break;
        }
    }


    /**
     * 通过用户名称获取数据
     *
     */
    public static function actionSetTitleOfData($field,$keyWords){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['user'],['user']);
        $params['body'] = self::actionSetMatch(1,$keyWords,['realname']);
        $rtn = $client->search($params);
        $dataTotal = $rtn['hits']['total'];
        if ($dataTotal>0){
            $paramPacOrProId = self::actionSetIndexType(['project_team','package_initiation'],['project_team','package_initiation']);
            $userData = $rtn['hits']['hits'];
            //如果大于0则组装用户id
            $userIdArr = [];
            foreach ($userData as $k => $v){
                $userIdArr[]=$v['_id'];
            }
            if (!empty($userIdArr)){
                //通过搜索团队成员获取资产包/项目的ID
                $paramPacOrProId['body'] = self::actionSetTerms(2,$userIdArr,$field);
                $pacOrProId = $client->search($paramPacOrProId);
                $pacOrProTeamTotal = $pacOrProId['hits']['total'];
                if ($pacOrProTeamTotal>0){
                    $pacOrProTeamData = $pacOrProId['hits']['hits'];
                    //拆分资产包/项目的ID
                    $pacAndProArr = [];
                    foreach ($pacOrProTeamData as $k => $v) {
                        if ($v['_index']=="package_initiation"){
                            $pacAndProArr['packageIdArr'][]=$v['_source']['package_id'];
                        }
                        if ($v['_index']=="project_team"){
                            $pacAndProArr['projectIdArr'][]=$v['_source']['project_id'];
                        }
                    }
                    return Responses::response200($pacAndProArr,$pacOrProTeamTotal);
                }
            }
            //没有资产包/项目ID返回空
            return [];
        }
        //没有资产包/项目ID返回空
        return [];
    }

    /**
     * 获取所有数据
     * $is_title 1是标题名称 2是用户名称
     */
    public static function actionSetAllData1($is_title,$keyWords,$orderNum,$size=10,$from=1){
        $dataInfo = self::actionSetIndexType(['package','project'],['package','project']);
        switch ($orderNum){
            case 0:
                $dataInfo['body']['sort']['_score']['order']='desc';
                break;
            case 1:
                $dataInfo['body']['sort']['created_at']['order']='asc';
                break;
            case 2:
                $dataInfo['body']['sort']['created_at']['order']='desc';
                break;
            default:
                $dataInfo['body']['sort']['_score']['order']='desc';
                break;
        }

        $dataInfo['size'] = $size;
        $dataInfo['from'] = $from;
        $dataInfo['body']['track_scores'] = true;
        $dataInfo['body']['query']['bool']['must'][]['term']['project_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        $dataInfo['body']['query']['bool']['must'][]['term']['package_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        if (!empty($is_title)&&$is_title==1){
            $dataInfo['body']=self::actionSetParamKeyWords($keyWords,["package_title","project_title"]);
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            switch ($orderNum){
                case 0:
                    $dataInfo['body']['sort']['_score']['order']='desc';
                    break;
                case 1:
                    $dataInfo['body']['sort']['created_at']['order']='asc';
                    break;
                case 2:
                    $dataInfo['body']['sort']['created_at']['order']='desc';
                    break;
                default:
                    $dataInfo['body']['sort']['_score']['order']='desc';
                    break;
            }
            $dataInfoArr = $client->search($dataInfo);
            $dataInfoHits  = $dataInfoArr['hits']['hits'];
            $dataInfoTotal = $dataInfoArr['hits']['total'];
            return Responses::response200($dataInfoHits,$dataInfoTotal);
        }else{
            $allData = self::actionSetTitleOfData(["leader","owner"],$keyWords);
            if (!empty($allData)){
                $packageIdArr = !empty($allData['data']['res']['packageIdArr'])?$allData['data']['res']['packageIdArr']:[];
                $projectIdArr = !empty($allData['data']['res']['projectIdArr'])?$allData['data']['res']['projectIdArr']:[];
                //获取资产包/项目信息
                $dataInfo['body']['query']['bool']['should'][]['terms']['package_id'] = $packageIdArr;
                $dataInfo['body']['query']['bool']['should'][]['terms']['project_id'] = $projectIdArr;
                $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
                switch ($orderNum){
                    case 0:
                        $dataInfo['body']['sort']['_score']['order']='desc';
                        break;
                    case 1:
                        $dataInfo['body']['sort']['created_at']['order']='desc';
                        break;
                    case 2:
                        $dataInfo['body']['sort']['created_at']['order']='asc';
                        break;
                    default:
                        $dataInfo['body']['sort']['_score']['order']='desc';
                        break;
                }
                $dataInfoArr = $client->search($dataInfo);
                $dataInfoHits  = $dataInfoArr['hits']['hits'];
                $dataInfoTotal = $dataInfoArr['hits']['total'];
                return Responses::response200($dataInfoHits,$dataInfoTotal);
            }
        }
    }

    /**
     * 获取资产包数据
     * $is_title 1是标题名称 2是用户名称
     */
    public static function actionSetPackageData($is_title,$keyWords,$orderNum,$size=10,$from=1,$paramArr){
        $packageInfo = self::actionSetIndexType(['package'],['package']);
        switch ($orderNum){
            case 0:
                $packageInfo['body']['sort']['_score']['order']='desc';
                break;
            case 1:
                $packageInfo['body']['sort']['_id']['order']='asc';
                break;
            case 2:
                $packageInfo['body']['sort']['_id']['order']='desc';
                break;
            default:
                $packageInfo['body']['sort']['_score']['order']='desc';
                break;
        }

        $packageInfo['body']['size'] = $size;
        $packageInfo['body']['from'] = $from;
        $packageInfo['body']['track_scores'] = true;  //关联度
        $packageInfo['body']['query']['bool']['must'][]['term']['package_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        //---本金数额-and-比较查询-
        if (!empty($paramArr['principal'])){
            $start = Yii::$app->params['getPackagePrice'][$paramArr['principal']]['start']; //["gte"=>0,"lte"=>999999999]
            $end   = Yii::$app->params['getPackagePrice'][$paramArr['principal']]['end']; //["gte"=>0,"lte"=>999999999]
            $packageInfo['body']['query']['bool']['must'][]['range']['principal'] = ["gte"=>$start,"lte"=>$end];
        }
        //---资产包类别-and-
        if (!empty($paramArr['category'])){
            $packageInfo['body']['query']['bool']['must'][]['term']['category'] = $paramArr['category'];
        }
        //---当前状态-and-
        if (!empty($paramArr['packageState'])) {
            $packageInfo['body']['query']['bool']['must'][]['term']['state'] = $paramArr['packageState'];
        }
        //---资产包类型-and-
        if (!empty($paramArr['packageType'])) {
            $packageInfo['body']['query']['bool']['must'][]['term']['type'] = $paramArr['packageType'];
        }
        //---省份地区-and-
        if (!empty($paramArr['city'])){
            $packageInfo['body']['query']['bool']['must'][]['term']['province'] = $paramArr['province'];
//            $packageInfo['body']['query']['bool']['must'][]['term']['city'] = "174";

//            $packageCityInfo = self::actionSetIndexType(['package'],['package']);
//            $zhengzeStr = "\(^".$paramArr['city'].",\)\|,".$paramArr['city'].",\|\($,".$paramArr['city']."\)\|\(^".$paramArr['city']."$\)";
//            $packageInfo['body']['query']['bool']['must'][]['regexp']['city']=$zhengzeStr;
            $packageInfo['body']['query']['bool']['must'][]['wildcard']['city']='*'.$paramArr['city'].'*';
//            $packageCityInfo['size'] = 10000;
//            //通过搜索项目行业获取资产包id
////            $params['query']['bool']['must'][]['terms'][$v]=$param;
//            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
//            $packageCityInfoData = $client->search($packageCityInfo);
//            $packageCityInfoHits = $packageCityInfoData['hits']['hits'];
//            $packageCityInfoTotal = $packageCityInfoData['hits']['total'];
//            $packageCityInfoPid = []; //存放资产包id
//            if ($packageCityInfoTotal>0){
//                foreach ($packageCityInfoHits as $k => $v) {
//                    $packageCityInfoPid[] = $v['_source']['package_id'];
//                }
//            }

        }else if (!empty($paramArr['province'])&&empty($paramArr['city'])){
            $packageInfo['body']['query']['bool']['must'][]['term']['province'] = $paramArr['province'];
        }
        //---行业分类-in-
        if (!empty($paramArr['industry'])){
            $industryArr = array_filter(explode(',',$paramArr['industry']));
            $projectInfo = self::actionSetIndexType(['project'],['project']);
            foreach ($industryArr as $k => $v) {
                $projectInfo['body']['query']['bool']['should'][]['wildcard']['industry']='*'.$v.'*';
            }
            $projectInfo['size'] = 10000;
            //通过搜索项目行业获取资产包id
//            $params['query']['bool']['must'][]['terms'][$v]=$param;
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $projectInfoData = $client->search($projectInfo);
            $projectHits = $projectInfoData['hits']['hits'];
            $projectTotal = $projectInfoData['hits']['total'];
            $projectPid = []; //存放资产包id
            if ($projectTotal>0){
                foreach ($projectHits as $k => $v) {
                    $projectPid[] = $v['_source']['package_id'];
                }
            }
            //通过资产包id获取信息
            $packageInfo['body']['query']['bool']['must'][]['terms']['_id']=$projectPid;
        }

        if (!empty($is_title)&&$is_title==1){
            if (!empty($packageInfo['body'])&&!empty($keyWords)) {
                $packageInfo['body']['query']['bool']['should'][]['multi_match']=[
                    'query' => $keyWords,
                    "fields" => 'package_title'
                ];
                $packageInfo['body']['query']['bool']['should'][]['wildcard']=[
                    'package_title' => "*".$keyWords."*"
                ];
            }
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $dataInfoPac = $client->search($packageInfo);
            $dataInfoHits  = $dataInfoPac['hits']['hits'];
            $dataInfoTotal = $dataInfoPac['hits']['total'];
            return Responses::response200($dataInfoHits,$dataInfoTotal);
        }else{
            $packageData = self::actionSetTitleOfData(["leader"],$keyWords);
            if (!empty($packageData)){
                $packageIdArr = $packageData['data']['res']['packageIdArr'];
                //获取资产包/项目信息
                $packageInfo['body']['query']['bool']['should'][]['terms']['_id'] = $packageIdArr;
                $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
                $dataInfoPac = $client->search($packageInfo);
                $dataInfoHits  = $dataInfoPac['hits']['hits'];
                $dataInfoTotal = $dataInfoPac['hits']['total'];
                return Responses::response200($dataInfoHits,$dataInfoTotal);
            }
        }
    }

    /**
     * 获取所有数据
     * $is_title 1是标题名称 2是用户名称
     */
    public static function actionSetAllData($is_title,$keyWords,$orderNum,$size=10,$from=1){
        $dataInfo = self::actionSetIndexType(['package','project'],['package','project']);
        switch ($orderNum){
            case 0:
                $dataInfo['body']['sort']['_score']['order']='desc';
                break;
            case 1:
                $dataInfo['body']['sort']['_id']['order']='asc';
                break;
            case 2:
                $dataInfo['body']['sort']['_id']['order']='desc';
                break;
            default:
                $dataInfo['body']['sort']['_score']['order']='desc';
                break;
        }

        $dataInfo['size'] = $size;
        $dataInfo['from'] = $from;
        $dataInfo['body']['track_scores'] = true;
        $dataInfo['body']['query']['bool']['must'][]['term']['project_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        $dataInfo['body']['query']['bool']['must'][]['term']['package_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        if (!empty($is_title)&&$is_title==1){
            $dataInfo['body']=self::actionSetParamKeyWords($keyWords,["package_title","project_title"]);
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $dataInfoArr = $client->search($dataInfo);
            $dataInfoHits  = $dataInfoArr['hits']['hits'];
            $dataInfoTotal = $dataInfoArr['hits']['total'];
            return Responses::response200($dataInfoHits,$dataInfoTotal);
        }else{
            $allData = self::actionSetTitleOfData(["leader","owner"],$keyWords);
            if (!empty($allData)){
                $packageIdArr = !empty($allData['data']['res']['packageIdArr'])?$allData['data']['res']['packageIdArr']:[];
                $projectIdArr = !empty($allData['data']['res']['projectIdArr'])?$allData['data']['res']['projectIdArr']:[];
                //获取资产包/项目信息
                $dataInfo['body']['query']['bool']['should'][]['terms']['package_id'] = $packageIdArr;
                $dataInfo['body']['query']['bool']['should'][]['terms']['project_id'] = $projectIdArr;
                $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
                $dataInfoArr = $client->search($dataInfo);
                $dataInfoHits  = $dataInfoArr['hits']['hits'];
                $dataInfoTotal = $dataInfoArr['hits']['total'];
                return Responses::response200($dataInfoHits,$dataInfoTotal);
            }
        }
    }

    /**
     * 获取项目数据
     * $is_title 1是标题名称 2是用户名称
     */
    public static function actionSetProjectData($is_title,$keyWords,$orderNum,$size=10,$from=1,$paramArr){
        $projectInfo = self::actionSetIndexType(['project'],['project']);
        $projectInfo['body']['size'] = $size;
        $projectInfo['body']['from'] = $from;
        $projectInfo['body']['track_scores'] = true;  //关联度
        switch ($orderNum){
            case 0:
                $projectInfo['body']['sort']['_score']['order']='desc';
                break;
            case 1:
                $projectInfo['body']['sort']['_id']['order']='asc';
                break;
            case 2:
                $projectInfo['body']['sort']['_id']['order']='desc';
                break;
            default:
                $projectInfo['body']['sort']['_score']['order']='desc';
                break;
        }

        $projectInfo['body']['query']['bool']['must'][]['term']['project_is_finished'] = 1; //过滤垃圾数据'0未完成，1已完成',
        //---本金数额--
        if (!empty($paramArr['principal'])){
            $start = Yii::$app->params['getPackagePrice'][$paramArr['principal']]['start']; //["gte"=>0,"lte"=>999999999]
            $end   = Yii::$app->params['getPackagePrice'][$paramArr['principal']]['end']; //["gte"=>0,"lte"=>999999999]
            $projectInfo['body']['query']['bool']['must'][]['range']['principal'] = ["gte"=>$start,"lte"=>$end];
        }
        //---当前状态--
        if (!empty($paramArr['packageState'])) {
            $projectInfo['body']['query']['bool']['must'][]['term']['status'] = $paramArr['packageState'];
        }
        //---单项目类别--
        if (!empty($paramArr['category'])){
            $projectInfo['body']['query']['bool']['must'][]['term']['category'] = $paramArr['category'];
        }
        //---诉讼状态--
        if ($paramArr['is_suit']>-2){
            $projectInfo['body']['query']['bool']['must'][]['term']['is_suit'] = $paramArr['is_suit'];
        }
        //---省份地区--
        if (!empty($paramArr['city'])){
            $projectInfo['body']['query']['bool']['should'][]['term']['province'] = $paramArr['province'];
            $projectInfo['body']['query']['bool']['must'][]['term']['city'] = $paramArr['city'];
        }else if (!empty($paramArr['province'])&&empty($paramArr['city'])){
            $projectInfo['body']['query']['bool']['must'][]['term']['province'] = $paramArr['province'];
        }
        //---抵押物类型--
        if (!empty($paramArr['mortgageType'])) {
            $mortgageTypeArr = array_filter(explode(',',$paramArr['mortgageType']));
            $projectInfo = self::actionSetIndexType(['project'],['project']);
            foreach ($mortgageTypeArr as $k => $v) {
                $projectInfo['body']['query']['bool']['should'][]['wildcard']['mortgage_type']='*'.$v.'*';
            }
            $projectInfo['size'] = 10000;
            //通过搜索项目行业获取项目id
//            $params['query']['bool']['must'][]['terms'][$v]=$param;
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $projectInfoData = $client->search($projectInfo);
            $projectHits = $projectInfoData['hits']['hits'];
            $projectTotal = $projectInfoData['hits']['total'];
            $projectId = []; //存放项目id
            if ($projectTotal>0){
                foreach ($projectHits as $k => $v) {
                    $projectId[] = $v['_id'];
                }
            }
            //通过资产包id获取信息
            $projectInfo['body']['query']['bool']['must'][]['terms']['_id']=$projectId;
        }
        //---行业分类--
        if (!empty($paramArr['industry'])) {
            $industryArr = array_filter(explode(',',$paramArr['industry']));
            $projectInfo = self::actionSetIndexType(['project'],['project']);
            foreach ($industryArr as $k => $v) {
                if ($v==1){
                    $projectInfo['body']['query']['bool']['should'][]['wildcard']['industry']='*'.$v;
                }else{
                    $projectInfo['body']['query']['bool']['should'][]['wildcard']['industry']='*'.$v.'*';
                }
            }
            $projectInfo['size'] = 10000;
            //通过搜索项目行业获取项目id
//            $params['query']['bool']['must'][]['terms'][$v]=$param;
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $projectInfoData = $client->search($projectInfo);
            $projectHits = $projectInfoData['hits']['hits'];
            $projectTotal = $projectInfoData['hits']['total'];
            $projectId = []; //存放项目id
            if ($projectTotal>0){
                foreach ($projectHits as $k => $v) {
                    $projectId[] = $v['_id'];
                }
            }
            //通过资产包id获取信息
            $projectInfo['body']['query']['bool']['must'][]['terms']['_id']=$projectId;
        }

        if (!empty($is_title)&&$is_title==1){
            if (!empty($projectInfo['body'])&&!empty($keyWords)){
                $projectInfo['body']['query']['bool']['should'][]['multi_match']=[
                    'query' => $keyWords,
                    "fields" => 'project_title'
                ];
                $projectInfo['body']['query']['bool']['should'][]['wildcard']=[
                    'project_title' => "*".$keyWords."*"
                ];
            }
            $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
            $dataInfoPro = $client->search($projectInfo);
            $dataInfoHits  = $dataInfoPro['hits']['hits'];
            $dataInfoTotal = $dataInfoPro['hits']['total'];
            return Responses::response200($dataInfoHits,$dataInfoTotal);
        }else{
            $projectData = self::actionSetTitleOfData(["owner"],$keyWords);
            if (!empty($projectData)){
                $projectIdArr = $projectData['data']['res']['packageIdArr'];
                //获取资产包/项目信息
                $projectInfo['body']['query']['bool']['should'][]['terms']['package_id'] = $projectIdArr;
                $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
                $dataInfoPro = $client->search($projectInfo);
                $dataInfoHits  = $dataInfoPro['hits']['hits'];
                $dataInfoTotal = $dataInfoPro['hits']['total'];
                return Responses::response200($dataInfoHits,$dataInfoTotal);
            }
        }
    }

    /**
     * 联想关键词
     */
    public function actionAjaxKeyWord(){
        $keyWords = Yii::$app->request->get('keyWords',''); //搜索的关键词
        $group = Yii::$app->request->get('group',1);        //搜索的分类
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();

        if (empty($keyWords)){
            $keyWords=' ';
        }
        switch ($group){
            case 1:
                $index = ['package','project','user'];
                $type = ['package','project','user'];
                $field = ["package_title", "realname","project_title"];
                $params = self::actionSetIndexType($index,$type);
                $params['body'] = self::actionSetParamKeyWords($keyWords,$field);
                $rtn = $client->search($params);
                break;
            case 2:
                $index = ['package','user'];
                $type = ['package','user'];
                $field = ["package_title", "realname"];
                $params = self::actionSetIndexType($index,$type);
                $params['body'] = self::actionSetParamKeyWords($keyWords,$field);
                $rtn = $client->search($params);
                break;
            case 3:
                $index = ['project','user'];
                $type = ['project','user'];
                $field = ["realname","project_title"];
                $params = self::actionSetIndexType($index,$type);
                $params['body'] = self::actionSetParamKeyWords($keyWords,$field);
                $rtn = $client->search($params);
                break;
            default:
                $index = ['package','project','user'];
                $type = ['package','project','user'];
                $field = ["package_title", "realname","project_title"];
                $params = self::actionSetIndexType($index,$type);
                $params['body'] = self::actionSetParamKeyWords($keyWords,$field);
                $rtn = $client->search($params);
                break;
        }
        //判断数据长度是否大于1
        $rtnTotal = $rtn['hits']['total'];
        $htmlDom = "";
        if ($rtnTotal>0){
            $rtnHits = $rtn['hits']['hits']; //数据array
            foreach ($rtnHits as $k => $v) {
                $urlStr = "/search-all?postion=".$group;
                if (!empty($v['highlight']['realname'])){
                    $realname = $v['_source']['realname'];
                    $url = $urlStr."&keyWords=".$realname.'&is_title=2';
                    $htmlStr = <<<HTMLSTR
                        <li><a href='$url'>$realname</a></li>
HTMLSTR;
                    $htmlDom.=$htmlStr;
                }
                if (!empty($v['highlight']['project_title'])){
                    $ProjectTitle = $v['_source']['project_title'];
                    $url = $urlStr."&keyWords=".$ProjectTitle.'&is_title=1&is_package=2';
                    $htmlStr = <<<HTMLSTR
                        <li><a href='$url'>$ProjectTitle</a></li>
HTMLSTR;
                    $htmlDom.=$htmlStr;
                }
                if (!empty($v['highlight']['package_title'])){
                    $PackageTitle = $v['_source']['package_title'];
                    $url = $urlStr."&keyWords=".$PackageTitle.'&is_title=1&is_package=1';
                    $htmlStr = <<<HTMLSTR
                        <li><a href='$url'>$PackageTitle</a></li>
HTMLSTR;
                    $htmlDom.=$htmlStr;
                }
            }
        }
        return json_encode(Responses::response200($htmlDom,$rtnTotal,"获取数据成功"));
    }

    /**
     * 设置索引
     * @param array $index
     * @param array $type
     */
    public static function actionSetIndexType(array $index,array $type){
        $params['index'] = $index;
        $params['type']  = $type;
        return $params;
    }


    /**
     * 分词搜索
     * @param $bool   1and 2or
     * @param $keyWords  关键词
     * @param $field     字段 ["package_title", "realname","project_title"]
     * //@param $mode  查询模式 （①分词查询，②模糊like查询）
     */
    public static function actionSetMatch($bool,$keyWords,array $field){
        if ($bool==1){
            $params['query']['bool']['must'][]['multi_match']=[
                'query' => $keyWords,
                "fields" => $field
            ];
        }else{
            $params['query']['bool']['should'][]['multi_match']=[
                'query' => $keyWords,
                "fields" => $field
            ];
        }
        return $params;
    }

    /**
     * 组装赛选条件---比较查询（金额）
     * @param $bool   1and 2or
     * @param $param  本金条件  ["gte"=>0,"lte"=>999999999]
     * @param $field  字段
     */
    public static function actionSetRange($bool,$param,$field){
        if ($bool==1){
            $params['query']['bool']['must'][]['range'][$field]=$param;
        }else{
            $params['query']['bool']['should'][]['range'][$field]=$param;
        }
        return $params;
    }


    /**
     * 组装赛选条件---term（and or查询）
     * @param $bool  1and 2or
     * @param $param
     * @param $field 字段
     */
    public static function actionSetTerm($bool,$param,$field){
        if ($bool==1){
            $params['query']['bool']['must'][]['term'][$field]=$param;
        }else{
            $params['query']['bool']['should'][]['term'][$field]=$param;
        }
        return $params;
    }


    /**
     * 组装赛选条件---terms（in查询）
     * @param $bool  1and 2or
     * @param $param [1,2,3]
     * @param $field 搜索的字段
     */
    public static function actionSetTerms($bool,$param,$field){
        if ($bool==1){
            if (is_array($field) && !empty($field)){
                foreach ($field as $k => $v){
                    $params['query']['bool']['must'][]['terms'][$v]=$param;
                }
            }else{
                $params['query']['bool']['must'][]['terms'][$field]=$param;
            }
        }else{
            if (is_array($field) && !empty($field)){
                foreach ($field as $k => $v){
                    $params['query']['bool']['should'][]['terms'][$v]=$param;
                }
            }else{
                $params['query']['bool']['should'][]['terms'][$field]=$param;
            }
        }

        return $params;
    }

    /**
     * 组装赛选条件---关键词
     */
    public static function actionSetParamKeyWords($keyWords,array $field,array $params=[]){
        if (!empty($params['query'])){
            $params['query']['bool']['must'][]['multi_match']=[
                'query' => $keyWords,
                "fields" => $field
            ];
        }else{
            $params['query']['bool']['should'][]['multi_match']=[
                'query' => $keyWords,
                "fields" => $field
            ];
            foreach ($field as $k => $v) {
                $params['query']['bool']['should'][]['wildcard']=[
                    $v => "*".$keyWords."*"
                ];
            }
        }

        $params['highlight']['pre_tags']=["<em>"];
        $params['highlight']['post_tags']=["<em>"];
        $params['highlight']['fields']=[
            "package_title" => new \stdClass(),
            "project_title" => new \stdClass(),
            "realname" => new \stdClass()
        ];
        return $params;
    }

    /**
     * 返回所有的用户
     */
    public static function actionGetUser(){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['user'],['user']);
        $params['size'] = 10000;
        $rtnUser = $client->search($params);
        $rtnUserHits = $rtnUser['hits']['hits'];
        $rtnUserTotal = $rtnUser['hits']['total'];
        return Responses::response200($rtnUserHits,$rtnUserTotal);
    }

    /**
     * 返回资产包团队
     */
    public static function actionGetPackageTeam(){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['package_initiation'],['package_initiation']);
        $params['size'] = 10000;
        $rtnPackTeam = $client->search($params);
        $rtnPackTeamHits = $rtnPackTeam['hits']['hits'];
        $rtnPackTeamTotal = $rtnPackTeam['hits']['total'];
        return Responses::response200($rtnPackTeamHits,$rtnPackTeamTotal);
    }

    /**
     * 返回项目团队
     */
    public static function actionGetProjectTeam(){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['project_team'],['project_team']);
        $params['size'] = 10000;
        $rtnProTeam = $client->search($params);
        $rtnProTeamHits = $rtnProTeam['hits']['hits'];
        $rtnProTeamTotal = $rtnProTeam['hits']['total'];
        return Responses::response200($rtnProTeamHits,$rtnProTeamTotal);
    }

    /**
     * 返回角色信息
     * @return array
     */
    public static function actionGetAuthitem(){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['auth_item'],['auth_item']);
        $params['size'] = 10000;
        $rtnRole = $client->search($params);
        $rtnRoleHits = $rtnRole['hits']['hits'];
        $rtnRoleTotal = $rtnRole['hits']['total'];
        return Responses::response200($rtnRoleHits,$rtnRoleTotal);
    }

    /**
     * 返回package信息
     * @return array
     */
    public static function actionGetPackageTransfer(){
        $client = ClientBuilder::create()->setHosts(self::$hosts)->build();
        $params = self::actionSetIndexType(['package_transfer'],['package_transfer']);
        $params['size'] = 10000;
        $rtnPackageTransfer = $client->search($params);
        $rtnPackageTransferHits = $rtnPackageTransfer['hits']['hits'];
        $rtnPackageTransferTotal = $rtnPackageTransfer['hits']['total'];
        return Responses::response200($rtnPackageTransferHits,$rtnPackageTransferTotal);
    }


    /**
     * 获取分词
     * @param $keyWords
     * @param $host
     */
    public static function actionGetAnalyzer($keyWords){
//        $a = ['/1/','/3/','/4/'];
//        $b = ['<em>1</em>','<em>3</em>','<em>4</em>'];
//        $c = 12345;
//            $d = preg_replace($a, $b, $c);
//            var_dump($d);die;
        //json也可以
        $data_string =  '{"analyzer":"ik_smart","text":"'.$keyWords.'"}';
        //curl验证成功
        $ch = curl_init("http://192.168.1.203:9200/_analyze");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ));

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        if (!empty(json_decode($result,true)['tokens'])){
            $normalStr = [];
            $tagStr = [];
            foreach (json_decode($result,true)['tokens'] as $k => $v) {
                $normalStr[] = '/'.$v['token'].'/i';
                $tagStr[] = '<em class="bcl">'.$v['token'].'</em>';
            }
            $data['normalStr'] = $normalStr;
            $data['tagStr'] = $tagStr;
            return $data;
        }
        return [];
    }
}